//
// Created by mio on 25-5-7.
//

#include "LoadBlanceServer.h"
#include "LoadBlanceConnection.h"
#include "../Net/EventLoop.h"

std::shared_ptr<LoadBlanceServer> LoadBlanceServer::Create(EventLoop* eventloop)
{
    std::shared_ptr<LoadBlanceServer> server(new LoadBlanceServer(eventloop));
    return server;
}

LoadBlanceServer::~LoadBlanceServer()
{
    for (auto iter : monitorInfos_)
    {
        if (iter.second)
        {
            delete iter.second;
            iter.second = nullptr;
        }
    }
}

LoadBlanceServer::LoadBlanceServer(EventLoop* eventloop) :
    TcpServer(eventloop),
    loop_(eventloop)
{

}

TcpConnectionPtr LoadBlanceServer::OnConnect(int fd)
{
    return std::make_shared<LoadBlanceConnection>(shared_from_this(), loop_->GetTaskScheduler().get(), fd);
}

void LoadBlanceServer::UpdateMonitor(const int fd, Monitor_body* info)
{
    std::lock_guard<std::mutex> lock(mtx_);
    monitorInfos_[fd] = info;

}

Monitor_body* LoadBlanceServer::GetMonitorInfo()
{
    std::lock_guard<std::mutex> lock(mtx_);
    // 先将map中的元素转转到vector中再排序
    std::vector<MonitorPair> vec(monitorInfos_.begin(), monitorInfos_.end());
    std::sort(vec.begin(), vec.end(), CmpByVale());
    // 因为是从小达到排序, 所以该容器的第一个就是最优服务器
    return vec[0].second;
}
